package com.alan.learn.common;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

/**
 * Created by liufan
 * 2019-12-04
 */
@Configuration
public class PropertiesUtil implements WebMvcConfigurer {

    private static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);
    private static volatile Properties props = null;

    /**
     * 获取remote.properties 文件的数据
     *
     * @param key 数据key
     * @return value key对应的value
     */
    public static String getRemoteProperty(String key) {
        if (StringUtils.isBlank(key)) {
            return StringUtils.EMPTY;
        }
        Properties property = getProperty("remote.properties");
        if (property == null) {
            return StringUtils.EMPTY;
        }
        return property.getProperty(key);
    }


    public static Properties getProperty(String fileName) {
        if (props == null) {
            synchronized (PropertiesUtil.class) {
                if (props == null) {
                    ClassPathResource resource = new ClassPathResource(fileName);
                    props = new Properties();
                    try {
                        try (InputStream is = resource.getInputStream()) {
                            BufferedReader bf = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                            props.load(bf);
                        }
                    } catch (Exception e) {
                        props = null;
                        logger.error("获取配置文件值[" + fileName + "]出错", e);
                    }
                }
            }
        }
        return props;
    }
}